<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="WTTWi2XnJ5">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Josefin Sans:300,300italic,400,400italic,700,700italic|Lobster:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lclong.top","root":"/","scheme":"Gemini","version":"7.7.1","exturl":true,"sidebar":{"position":"left","display":"post","padding":20,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="这篇文章是我在学校大数据课的一篇论文，有兴趣的可以详细了解，由于是最初最初学习，使用knn算法进行一个简单的分析。">
<meta property="og:type" content="article">
<meta property="og:title" content="基于KNN算法的NBA球员数据分析">
<meta property="og:url" content="https://lclong.top/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="Zlatanlong&#39;s T-blog">
<meta property="og:description" content="这篇文章是我在学校大数据课的一篇论文，有兴趣的可以详细了解，由于是最初最初学习，使用knn算法进行一个简单的分析。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://lclong.top/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/%E5%9B%BE5-1%E4%BA%A4%E5%8F%89%E9%AA%8C%E8%AF%81%E7%BB%93%E6%9E%9C.png">
<meta property="og:image" content="https://lclong.top/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/%E5%9B%BE5-2%E6%A0%B8%E5%BF%83%E4%BB%A3%E7%A0%81%E9%AA%8C%E8%AF%81.png">
<meta property="article:published_time" content="2019-06-01T08:21:35.000Z">
<meta property="article:modified_time" content="2019-06-01T08:21:35.000Z">
<meta property="article:author" content="Zlatanlong">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="knn">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://lclong.top/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/%E5%9B%BE5-1%E4%BA%A4%E5%8F%89%E9%AA%8C%E8%AF%81%E7%BB%93%E6%9E%9C.png">

<link rel="canonical" href="https://lclong.top/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>基于KNN算法的NBA球员数据分析 | Zlatanlong's T-blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zlatanlong's T-blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">Lakers is Championship!</h1>
      
  </div>

  <div class="site-nav-right"></div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">31</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">23</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">38</span></a>

  </li>
        <li class="menu-item menu-item-aboutme">

    <a href="/aboutme/" rel="section"><i class="fa fa-fw fa-user"></i>博主</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lclong.top/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Zlatanlong">
      <meta itemprop="description" content="生活就像巧克力🍫">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zlatanlong's T-blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          基于KNN算法的NBA球员数据分析
        </h2>

        <div class="post-meta">
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-06-01 16:21:35" itemprop="dateCreated datePublished" datetime="2019-06-01T16:21:35+08:00">2019-06-01</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%A4%A7%E6%95%B0%E6%8D%AE/" itemprop="url" rel="index">
                    <span itemprop="name">大数据</span>
                  </a>
                </span>
            </span>

          
            <span id="/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/" class="post-meta-item leancloud_visitors" data-flag-title="基于KNN算法的NBA球员数据分析" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">评论次数：</span>
    
    <a title="valine" href="/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>5.4k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>14 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>这篇文章是我在学校大数据课的一篇论文，有兴趣的可以详细了解，由于是最初最初学习，使用knn算法进行一个简单的分析。</p>
<a id="more"></a>

<h1 id="一、研究意义"><a href="#一、研究意义" class="headerlink" title="一、研究意义"></a>一、研究意义</h1><p>NBA的篮球哲学，随着金州勇士队连续闯入五年闯入总决赛，正在发生巨大的转变，三分成为了球队获胜的必要因素，联盟规则偏向进攻球员的转变，而本世纪初期铁血的防守理论已经无法适应新的环境。于此同时带来的就是球员位置的飘忽不定，每个球队都有小个阵容，球员的篮球习惯不同，在场上每套阵容安排时的司职位置也就不同。我使用球员的场均得分，篮板，助攻，抢断，盖帽来评估球员的场上位置。可以为教练和资深球迷提供了数据支持。</p>
<h1 id="二、数据描述"><a href="#二、数据描述" class="headerlink" title="二、数据描述"></a>二、数据描述</h1><p>Espn提供了NBA的篮球数据，供球迷和NBA分析师使用，这里我使用requests库来发送http请求，使用BeautifulSoup库解析html。数据来源网站即是<span class="exturl" data-url="aHR0cDovL3d3dy5lc3BuLmNvbQ==" title="http://www.espn.com">espn官网<i class="fa fa-external-link"></i></span>。</p>
<p><strong>表2-1 数据属性结构</strong></p>
<table>
<thead>
<tr>
<th>属性</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>场均上场时间min</td>
<td>预处理依据</td>
</tr>
<tr>
<td>场均得分pts</td>
<td>判断依据</td>
</tr>
<tr>
<td>场均篮板reb</td>
<td>判断依据</td>
</tr>
<tr>
<td>场均助攻ast</td>
<td>判断依据</td>
</tr>
<tr>
<td>场均抢断stl</td>
<td>判断依据</td>
</tr>
<tr>
<td>场均篮板blk</td>
<td>判断依据</td>
</tr>
<tr>
<td>场上位置</td>
<td>标签label</td>
</tr>
</tbody></table>
<p>如表2-1所示，我爬取了2018-2019赛季常规赛30个球队每名球员的</p>
<ul>
<li>场均上场时间min，</li>
<li>场均得分pts，</li>
<li>场均篮板reb，</li>
<li>场均助攻ast，</li>
<li>场均抢断stl，</li>
<li>场均篮板blk，</li>
<li>场上位置</li>
</ul>
<p>共7个属性，536条数据。其中<code>min</code>作为预处理时排除噪声数据的依据，<code>场均得分pts，场均篮板reb，场均助攻ast，场均抢断stl，场均篮板blk</code>五项属性作为判断球员场上位置的数据依据，而球员<code>场上位置</code>作为<strong>标签label</strong>。通过numpy库的save方法将前六条数据和标签分别保存，如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ori_data = transpose([min_data_list, pts_data_list, reb_data_list, ast_data_list, stl_data_list, blk_data_list])</span><br><span class="line">save(<span class="string">"ori_data.npy"</span>, ori_data)</span><br><span class="line">save(<span class="string">"label_data.npy"</span>, label_list)</span><br></pre></td></tr></table></figure>

<p><strong>预处理：</strong>由于每个球员场均上场时间过小时，其篮球数据可能不准确，因此将场均上场时间min大于8分钟的数据保留，其他数据删除，相关代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 预处理开始</span></span><br><span class="line">    ori_dataSet = load(<span class="string">"ori_data.npy"</span>)</span><br><span class="line">    label = load(<span class="string">"label_data.npy"</span>)</span><br><span class="line">    dataSet = hstack((ori_dataSet, transpose([label])))</span><br><span class="line">    filter_dataSet = zeros(shape=(<span class="number">1</span>,<span class="number">7</span>))</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(len(dataSet)):</span><br><span class="line">        <span class="keyword">if</span> float(dataSet[i,<span class="number">0</span>]) &gt; <span class="number">8</span>:</span><br><span class="line">            filter_dataSet = vstack((filter_dataSet,dataSet[i]))</span><br><span class="line">    labels = filter_dataSet[<span class="number">1</span>:,<span class="number">-1</span>]</span><br><span class="line">    filter_dataSet  = filter_dataSet[<span class="number">1</span>:,<span class="number">1</span>:<span class="number">-1</span>].astype(float)</span><br><span class="line"><span class="comment"># 预处理结束</span></span><br></pre></td></tr></table></figure>

<p><strong>归一化：</strong>由于每个属性的权值不同，这里使用归一化方式处理每个属性，相关代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 归一化操作开始</span></span><br><span class="line">    maxVals = filter_dataSet.max(<span class="number">0</span>)</span><br><span class="line">    minVals = filter_dataSet.min(<span class="number">0</span>)</span><br><span class="line">    ranges = maxVals - minVals</span><br><span class="line">    m = filter_dataSet.shape[<span class="number">0</span>]</span><br><span class="line">    normDataSet = (filter_dataSet - tile(minVals, (m,<span class="number">1</span>))) / tile(ranges, (m,<span class="number">1</span>))</span><br><span class="line"><span class="comment"># 归一化操作结束</span></span><br></pre></td></tr></table></figure>

<h1 id="三、模型描述"><a href="#三、模型描述" class="headerlink" title="三、模型描述"></a>三、模型描述</h1><p>主要函数如下：</p>
<ul>
<li><p><code>createDataSet()</code>：读取保存的数据，并进行预处理，归一化操作；    </p>
<ul>
<li>读取数据</li>
<li>将data和label水平拼接成矩阵temp</li>
<li>对temp行循环，将min满足要求的数据添加到mydata</li>
<li>mydata即为预处理后数据，按列取mydata最大最小值</li>
<li>以最大值减最小值ranges为分母，将mydata归一化</li>
</ul>
</li>
<li><p><code>classify(input, dataSet, label, k)</code>：使用KNN算法进行归类，input为期望归类的数据，dataSet是判断依据集合，label是对应的标签，k为每次判断时邻居个数，合理的k值根据下文提到的交叉判断得出。</p>
<ul>
<li>通过两个矩阵运算来求欧式距离</li>
<li>对距离排序</li>
<li>从排序后的K个数据中寻找label属性最多的数据，即为所求</li>
<li>main()：程序的主入口，输入input数据，并得出结果。</li>
<li>创建数据</li>
<li>执行核心算法classify（）</li>
</ul>
</li>
<li><p><code>cross_validate.py</code> 设计好算法后用于交叉验证，计算出最优K值。</p>
<ul>
<li>对原数据2，8分类，其中20%做测试数据，80%做训练数据</li>
<li>用20%的训练数据依次在训练数据中执行算法，并得到结果集合</li>
<li>将结果集合和实际数据对比，求出错误个数，错误率</li>
<li>使用不同的K值重复上两步操作，得到错误率最小的K</li>
</ul>
</li>
</ul>
<h1 id="四、算法实现"><a href="#四、算法实现" class="headerlink" title="四、算法实现"></a>四、算法实现</h1><p>因为算法较为简单，一个py跑到底</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">##给出训练数据以及对应的类别</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">createDataSet</span><span class="params">()</span>:</span></span><br><span class="line"><span class="comment"># 预处理开始</span></span><br><span class="line">ori_dataSet = load(<span class="string">"ori_data.npy"</span>)</span><br><span class="line">label = load(<span class="string">"label_data.npy"</span>)</span><br><span class="line">dataSet = hstack((ori_dataSet, transpose([label])))</span><br><span class="line">filter_dataSet = zeros(shape=(<span class="number">1</span>,<span class="number">7</span>))</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(len(dataSet)):</span><br><span class="line"><span class="keyword">if</span> float(dataSet[i,<span class="number">0</span>]) &gt; <span class="number">8</span>:</span><br><span class="line">filter_dataSet = vstack((filter_dataSet,dataSet[i]))</span><br><span class="line">labels = filter_dataSet[<span class="number">1</span>:,<span class="number">-1</span>]</span><br><span class="line">filter_dataSet  = filter_dataSet[<span class="number">1</span>:,<span class="number">1</span>:<span class="number">-1</span>].astype(float)</span><br><span class="line"><span class="comment"># 预处理结束</span></span><br><span class="line"><span class="comment"># 归一化操作开始</span></span><br><span class="line">maxVals = filter_dataSet.max(<span class="number">0</span>)</span><br><span class="line">minVals = filter_dataSet.min(<span class="number">0</span>)</span><br><span class="line">ranges = maxVals - minVals</span><br><span class="line">m = filter_dataSet.shape[<span class="number">0</span>]</span><br><span class="line">normDataSet = (filter_dataSet - tile(minVals, (m,<span class="number">1</span>))) / tile(ranges, (m,<span class="number">1</span>))</span><br><span class="line"><span class="comment"># 归一化操作结束</span></span><br><span class="line"><span class="keyword">return</span> normDataSet, labels, ranges, minVals</span><br><span class="line"></span><br><span class="line"><span class="comment">###通过KNN进行分类</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">classify</span><span class="params">(input, dataSet, label, k)</span>:</span></span><br><span class="line">    dataSize = dataSet.shape[<span class="number">0</span>]</span><br><span class="line">    <span class="comment">####计算欧式距离</span></span><br><span class="line">    diff = tile(input, (dataSize, <span class="number">1</span>)) - dataSet</span><br><span class="line">    sqdiff = diff ** <span class="number">2</span></span><br><span class="line">    squareDist = sum(sqdiff, axis=<span class="number">1</span>)  <span class="comment">###行向量分别相加，从而得到新的一个行向量</span></span><br><span class="line">    dist = squareDist ** <span class="number">0.5</span></span><br><span class="line">    <span class="comment">##对距离进行排序</span></span><br><span class="line">    sortedDistIndex = argsort(dist)  <span class="comment">##argsort()根据元素的值从大到小对元素进行排序，返回下标</span></span><br><span class="line">    classCount = &#123;&#125;</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(k):</span><br><span class="line">        voteLabel = label[sortedDistIndex[i]]</span><br><span class="line">        <span class="comment">###对选取的K个样本所属的类别个数进行统计</span></span><br><span class="line">        classCount[voteLabel] = classCount.get(voteLabel, <span class="number">0</span>) + <span class="number">1</span></span><br><span class="line">        <span class="comment"># classCount.clear()</span></span><br><span class="line">    <span class="comment">###选取出现的类别次数最多的类别</span></span><br><span class="line">    maxCount = <span class="number">0</span></span><br><span class="line">    classes  = <span class="string">''</span></span><br><span class="line">    <span class="keyword">for</span> key, value <span class="keyword">in</span> classCount.items():</span><br><span class="line">        <span class="keyword">if</span> value &gt; maxCount:</span><br><span class="line">            maxCount = value</span><br><span class="line">            classes = key</span><br><span class="line">    <span class="keyword">return</span> classes</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    normDataSet, labels, ranges, minVals = createDataSet()</span><br><span class="line">    input = array([<span class="number">18</span>,<span class="number">8</span>,<span class="number">3</span>,<span class="number">0.3</span>,<span class="number">2.1</span>])</span><br><span class="line">    normInput = (input - minVals) / ranges <span class="comment">#对输入的菜品进行归一化处理</span></span><br><span class="line">    K = <span class="number">17</span></span><br><span class="line">print(<span class="string">"测试数据为:"</span>,input,<span class="string">"分类结果为："</span>,classify(normInput, normDataSet, labels, K))</span><br><span class="line"></span><br><span class="line">cross_validata.py:</span><br><span class="line"><span class="keyword">from</span> numpy <span class="keyword">import</span> *</span><br><span class="line"><span class="keyword">import</span> main</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line"><span class="comment"># 预处理开始</span></span><br><span class="line">ori_dataSet = load(<span class="string">"ori_data.npy"</span>)</span><br><span class="line">label = load(<span class="string">"label_data.npy"</span>)</span><br><span class="line">my_label = label</span><br><span class="line"><span class="comment"># my_label 相当于取每个位置的最后一个位置来验证</span></span><br><span class="line"><span class="comment"># PG,SG =&gt; G</span></span><br><span class="line"><span class="comment"># SF,PF =&gt; F</span></span><br><span class="line"><span class="comment"># C     =&gt; C</span></span><br><span class="line"><span class="comment"># 因为现在篮球位置飘忽摇摆，所以能验证出是前场球员还是后场球员即是好的算法</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(label.shape[<span class="number">0</span>]):</span><br><span class="line">    my_label[i] = label[i][<span class="number">-1</span>]</span><br><span class="line"></span><br><span class="line">dataSet = hstack((ori_dataSet, transpose([my_label])))</span><br><span class="line">filter_dataSet = zeros(shape=(<span class="number">1</span>,<span class="number">7</span>))</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(len(dataSet)):</span><br><span class="line">    <span class="keyword">if</span> float(dataSet[i,<span class="number">0</span>]) &gt; <span class="number">8</span>:</span><br><span class="line">        filter_dataSet = vstack((filter_dataSet,dataSet[i]))</span><br><span class="line">filter_dataSet = filter_dataSet[<span class="number">1</span>:]</span><br><span class="line"><span class="comment"># 预处理结束</span></span><br><span class="line"><span class="comment"># 选取训练集和验证集</span></span><br><span class="line">vaildate_range = <span class="number">0.2</span> <span class="comment">#选取多少数据进行验证</span></span><br><span class="line">trian_set = filter_dataSet[<span class="number">0</span>:int(filter_dataSet.shape[<span class="number">0</span>] * vaildate_range), :]</span><br><span class="line">vaildate_set = filter_dataSet[int(filter_dataSet.shape[<span class="number">0</span>] * vaildate_range):, :]</span><br><span class="line">trian_only_dataSet = trian_set[:, <span class="number">1</span>:<span class="number">-1</span>].astype(float)</span><br><span class="line">trian_labels = trian_set[:, <span class="number">-1</span>]</span><br><span class="line">vaildate_only_dataSet = vaildate_set[:, <span class="number">1</span>:<span class="number">-1</span>].astype(float)</span><br><span class="line">vaildate_labels = vaildate_set[:, <span class="number">-1</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 进行验证</span></span><br><span class="line">test_count = trian_set.shape[<span class="number">0</span>]</span><br><span class="line">k_err_di = &#123;&#125;</span><br><span class="line">k_err = []</span><br><span class="line"><span class="keyword">for</span> k <span class="keyword">in</span> range(<span class="number">1</span>,<span class="number">30</span>):</span><br><span class="line">    err_time = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(test_count):</span><br><span class="line">        temp_test_label = main.classify(trian_only_dataSet[i], vaildate_only_dataSet, vaildate_labels, k)</span><br><span class="line">        <span class="keyword">if</span> temp_test_label != trian_labels[i]:</span><br><span class="line">            err_time += <span class="number">1</span></span><br><span class="line">    k_err.append(err_time/test_count)</span><br><span class="line">    k_err_di[k] = err_time/test_count</span><br><span class="line">print(k_err_di)</span><br><span class="line">xs = arange(len(k_err)) + <span class="number">1</span></span><br><span class="line">plt.plot(xs,k_err)</span><br><span class="line">plt.xlabel(<span class="string">'K'</span>)</span><br><span class="line">plt.ylabel(<span class="string">'Error'</span>)</span><br><span class="line">plt.title(<span class="string">'Error vs K'</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>

<h1 id="五、运行结果及意义说明"><a href="#五、运行结果及意义说明" class="headerlink" title="五、运行结果及意义说明"></a>五、运行结果及意义说明</h1><p><img src="/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/%E5%9B%BE5-1%E4%BA%A4%E5%8F%89%E9%AA%8C%E8%AF%81%E7%BB%93%E6%9E%9C.png" alt="图5-1交叉验证结果"></p>
<p>交叉验证结果如图5-1, 因为现代篮球的位置区分率不高，所以按照5个传统位置来分，错误率较高；因此使用F前场，C中锋，G后场，三种球员位置来进行交叉验证。在<code>K=(1:30)</code>区间内进行验证，发现<code>K = 17</code>时错误率最低，因此选K = 17。</p>
<p><img src="/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/%E5%9B%BE5-2%E6%A0%B8%E5%BF%83%E4%BB%A3%E7%A0%81%E9%AA%8C%E8%AF%81.png" alt="图5-2核心代码验证"></p>
<p>核心代码验证结果如图5-2，所示，输入分别为场均得分，篮板，助攻，抢断，盖帽，结果符合现实篮球规律。</p>
<h1 id="六、总结"><a href="#六、总结" class="headerlink" title="六、总结"></a>六、总结</h1><p>在实现这次基于KNN算法的应用过程中，自己亲身体验到了一种分类算法的实现过程，同时也深刻了解了该算法的经典和不足之处，在进行交叉验证时，发现错误率均较高，根据核心分析原因，是因为label不同的一些数据分布在一个较近的区域，因此不容易区分，同时这也是KNN算法的不足之处：对于区域内模糊的数据难以区分。这也激起了我学习其他分类算法的兴趣，对比各种算法的优劣，在合适的应用环境中选择合适的算法。</p>
<p>经过2个学时的学习，我对于大数据的概念已经有了一定的认识，也已经体验了一次数据分析的过程，相信在以后的学习和研究过程中，能够不断丰富相关知识，同时也不断应用所学知识解决问题。</p>

    </div>

    
    
    
      
  <div class="popular-posts-header">相关文章</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\2019\07\01\基于BP神经网络的NBA球员薪资评估\" rel="bookmark">基于BP神经网络的NBA球员薪资评估</a></div>
    </li>
  </ul>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Zlatanlong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://lclong.top/2019/06/01/%E5%9F%BA%E4%BA%8EKNN%E7%AE%97%E6%B3%95%E7%9A%84NBA%E7%90%83%E5%91%98%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90/" title="基于KNN算法的NBA球员数据分析">https://lclong.top/2019/06/01/基于KNN算法的NBA球员数据分析/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <span class="exturl" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLXNhLzQuMC96aC1DTg=="><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</span> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
              <a href="/tags/knn/" rel="tag"><i class="fa fa-tag"></i> knn</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/05/03/Mac%E7%B3%BB%E7%BB%9F%E5%B7%A5%E5%85%B7%E6%80%BB%E7%BB%93/" rel="prev" title="Mac系统工具文件命令大全(持续更新)">
      <i class="fa fa-chevron-left"></i> Mac系统工具文件命令大全(持续更新)
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/07/01/%E5%9F%BA%E4%BA%8EBP%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C%E7%9A%84NBA%E7%90%83%E5%91%98%E8%96%AA%E8%B5%84%E8%AF%84%E4%BC%B0/" rel="next" title="基于BP神经网络的NBA球员薪资评估">
      基于BP神经网络的NBA球员薪资评估 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  
  </div>


          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#一、研究意义"><span class="nav-number">1.</span> <span class="nav-text">一、研究意义</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二、数据描述"><span class="nav-number">2.</span> <span class="nav-text">二、数据描述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#三、模型描述"><span class="nav-number">3.</span> <span class="nav-text">三、模型描述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#四、算法实现"><span class="nav-number">4.</span> <span class="nav-text">四、算法实现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#五、运行结果及意义说明"><span class="nav-number">5.</span> <span class="nav-text">五、运行结果及意义说明</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#六、总结"><span class="nav-number">6.</span> <span class="nav-text">六、总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Zlatanlong"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Zlatanlong</p>
  <div class="site-description" itemprop="description">生活就像巧克力🍫</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">23</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">31</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL3psYXRhbmxvbmc=" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;zlatanlong"><i class="fa fa-fw fa-github"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOmxvbmctdHhnY0Bmb3htYWlsLmNvbQ==" title="E-Mail → mailto:long-txgc@foxmail.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      关注列表
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9sZWZsYWNvbi5naXRodWIuaW8v" title="https:&#x2F;&#x2F;leflacon.github.io&#x2F;">leflacon</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9ib2Jib3NzLmdpdGh1Yi5pby8=" title="https:&#x2F;&#x2F;bobboss.github.io&#x2F;">BobBoss</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cDovL29wdGltaXN0aWNhdC54eXovdXNlcj91c2VySWQ9bHpkY2w=" title="http:&#x2F;&#x2F;optimisticat.xyz&#x2F;user?userId&#x3D;lzdcl">lzdcl</span>
        </li>
    </ul>
  </div>

      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 2018 – 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zlatanlong</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">166k</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> 强力驱动 v4.2.1
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> v7.7.1
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script color='0,0,255' opacity='0.5' zIndex='-1' count='99' src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@latest/canvas-nest-nomobile.min.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'H5inyassVpcpItLTuMJH9aBg-gzGzoHsz',
      appKey     : 'mBzB6QB3deD6zw8YEIKVQdzz',
      placeholder: "快来说两句吧。。。",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
